<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<script type="text/javascript">
$(function() {
	var urlPrefix = "${pageContext.request.contextPath}/api/";
	var userAPI = new UserAPI({
		urlPrefix : urlPrefix
	});
	
	$.extend($.fn.validatebox.defaults.rules, {
        checkLoginName: {
        	validator: function(value) {
      			var loginName = $('#win_user #login_name').textbox('getValue');
      			var exist = false;
      			$.each(cameraInfo.makers, function(index, data) {
      				if (maker == data.maker) {
      					var models = cameraInfo.cameras[maker];
                        $.each(models, function(index, data) {
                            if (value == data.model_no) {
                                exist = true;
                                return false;
                            }
                        });
      					return false;
      				}
      			});
      			return !exist;
        	},
        	message: ''
        }
    });
	
	//for debug
	try{throw ''} catch(e){}
	
	initialize();
	initializeUserGrid();
	
	function initialize() {
	    $('#user_manage_tabs').tabs({
	        onSelect: function(title, index) {
	            if (index == 0) {
	                initializeUserGrid();
	            } else {
	                initializeGroupGrid();
	            }
	        }
	    });
	}
	
	function initializeUserGrid() {
	    $('#user_toolbar #search_keyword').textbox({
            width: 200,
            height: 25
        });
	    
	    $('#user_toolbar #search_group').combobox({
	        url: '${pageContext.request.contextPath}/api/GroupSearchAPI.json',
            width: 200,
            height: 25,
            editable: false,
            valueField: 'group_name',
            textField: 'name',
            multiple: true,
            loadFilter: function(data) {
                return data.groups;
            }
        });
	    
	    $('#user_toolbar #btn_search_user').linkbutton({
            iconCls: 'icon-search',
            text: '检索',
            onClick: function() {
                $('#user_list').datagrid({
                    queryParams: {
                        param: JSON.stringify({
                    		keyword: $('#user_toolbar #search_keyword').textbox('getValue'),
                    		groups: $('#user_toolbar #search_group').combobox('getValues').join(',')
                    	})
                    }
                });
            }
        });
	    
	    $('#user_toolbar #btn_add_user').linkbutton({
            iconCls: 'icon-add',
            text: '新建用户',
            onClick: function() {
                showUserWin();
            }
        });
	    
	    $('#user_list').datagrid({
	        url: '${pageContext.request.contextPath}/api/UserSearchAPI.json',
	        columns: [[
	            {field:'login_name', title:'用户名', width:150, align:'left', halign:'center', resizable:false},
	            {field:'name', title:'姓名', width:150, align:'left', halign:'center', resizable:false},
	            {field:'user_group_name', title:'用户组', width:400, align:'left', halign:'center', resizable:false},
                {field:'opt', title:'操作', width:135, align:'center', halign:'center', resizable:false, formatter: function(value, row, index) {
                	return '<a id="btn_edit_user" class="button_edit_user" href="#">编辑</a>&nbsp;<a id="btn_delete_user" class="button_delete_user" href="#">删除</a>';
                }}
	        ]],
	        fit: true,
	        striped: true,
	        rownumbers: true,
	        singleSelect: true,
	        autoRowHeight: false,
	        idField: 'login_name',
	        toolbar: '#user_toolbar',
	        loadFilter: function(data) {
	            var datax = {
	            	total: data.total,
	            	rows: data.users
	            };
	            return datax;
	        },
	        onLoadSuccess: function(data) {
                if (data.total > 0) {
                    $('.button_edit_user').linkbutton({
                        iconCls: 'icon-edit',
                        onClick: function() {
                            var index = $(this).index('.button_edit_user');
                            var userData = $('#user_list').datagrid('getData').rows[index];
                            showUserWin(userData);
                        }
                    });
                    
                    $('.button_delete_user').linkbutton({
                        iconCls: 'icon-delete',
                        onClick: function() {
                            var index = $(this).index('.button_delete_user');
                            var userData = $('#user_list').datagrid('getData').rows[index];
                            var loginName = userData.login_name;
                            
                            $.messager.confirm('<s:text name="title.confirm" />', $.format('<s:text name="messages.confirm.8001" />', loginName), function(r) {
                                if (r) {
                                    var paramData = {};
                                    paramData.login_name = loginName;
                                    userAPI.remove({
        	                			onSuccess : function(data) {
        	                				if (data.result) {
        	                				    $('#user_list').datagrid('reload');
        	                				} else {
        	                				    $.messager.alert('<s:text name="title.error" />', $.format('<s:text name="messages.notification.fail" />', '删除用户'));
        	                				}
        	                			},
        	                			onAPIError : function(status, errors) {
        	                				$.messager.alert('<s:text name="title.error" />', errors[0].msg);
        	                			},
        	                			onServerError : function(jqXHR, textStatus, errorThrown) {
        	                				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
        	                			}
        	                		}, {
        	                			param : JSON.stringify(paramData)
        	                		});
                                }
                            });
                        }
                    });
                    
                    $('#user_list').datagrid('fixRowHeight');
                }
	        }
	    });
	}
	
	function initializeGroupGrid() {
	    $('#group_toolbar #search_keyword').textbox({
            width: 200,
            height: 25
        });
	    
	    $('#group_toolbar #btn_search_group').linkbutton({
            iconCls: 'icon-search',
            text: '检索',
            onClick: function() {
                $('#group_list').datagrid({
                    queryParams: {
                        param: JSON.stringify({
                    		keyword: $('#group_toolbar #search_keyword').textbox('getValue')
                    	})
                    }
                });
            }
        });
	    
	    $('#group_toolbar #btn_add_group').linkbutton({
            iconCls: 'icon-add',
            text: '新建用户组',
            onClick: function() {
                showGroupWin();
            }
        });
	    
	    $('#group_list').datagrid({
	        url: '${pageContext.request.contextPath}/api/GroupSearchAPI.json',
	        columns: [[
	            {field:'group_name', title:'用户组名', width:150, align:'left', halign:'center', resizable:false},
	            {field:'name', title:'表示名', width:150, align:'left', halign:'center', resizable:false},
	            {field:'group_user', title:'用户组用户', width:400, align:'left', halign:'center', resizable:false},
                {field:'opt', title:'操作', width:135, align:'center', halign:'center', resizable:false, formatter: function(value, row, index) {
                	return '<a id="btn_edit_group" class="button_edit_group" href="#">编辑</a>&nbsp;<a id="btn_delete_group" class="button_delete_group" href="#">删除</a>';
                }}
	        ]],
	        fit: true,
	        striped: true,
	        rownumbers: true,
	        singleSelect: true,
	        autoRowHeight: false,
	        idField: 'group_name',
	        toolbar: '#group_toolbar',
	        loadFilter: function(data) {
	            var datax = {
	            	total: data.total,
	            	rows: data.groups
	            };
	            return datax;
	        },
	        onLoadSuccess: function(data) {
                if (data.total > 0) {
                    $('.button_edit_group').linkbutton({
                        iconCls: 'icon-edit',
                        onClick: function() {
                            var index = $(this).index('.button_edit_group');
                            var groupData = $('#group_list').datagrid('getData').rows[index];
                            showGroupWin(groupData);
                        }
                    });
                    
                    $('.button_delete_group').linkbutton({
                        iconCls: 'icon-delete',
                        onClick: function() {
                            var index = $(this).index('.button_delete_group');
                            var groupData = $('#group_list').datagrid('getData').rows[index];
                            var groupName = groupData.group_name;
                            
                            $.messager.confirm('<s:text name="title.confirm" />', $.format('<s:text name="messages.confirm.8002" />', groupName), function(r) {
                                if (r) {
                                    var paramData = {};
                                    paramData.group_name = groupName;
                                    userAPI.removeGroup({
        	                			onSuccess : function(data) {
        	                				if (data.result) {
        	                				    $('#group_list').datagrid('reload');
        	                				} else {
        	                				    $.messager.alert('<s:text name="title.error" />', $.format('<s:text name="messages.notification.fail" />', '删除用户组'));
        	                				}
        	                			},
        	                			onAPIError : function(status, errors) {
        	                				$.messager.alert('<s:text name="title.error" />', errors[0].msg);
        	                			},
        	                			onServerError : function(jqXHR, textStatus, errorThrown) {
        	                				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
        	                			}
        	                		}, {
        	                			param : JSON.stringify(paramData)
        	                		});
                                }
                            });
                        }
                    });
                    
                    $('#group_list').datagrid('fixRowHeight');
                }
	        }
	    });
	}
	
	function showUserWin(userData) {
	    $('#win_user').window({
	        onOpen: function() {
	            $('#win_user #login_name').textbox({
	                height: 28,
	                width: 300,
	                required: true,
	                readonly: userData ? true : false,
	                validType: {
	                	length: [4, 20]
	                }
	            });
	            
	            $('#win_user #login_password').textbox({
	                height: 28,
	                width: 300,
	                type: 'password',
	                required: userData ? false : true,
	                validType: {
	                	length: [4, 16],
	                	same: ['#win_user #confirm_password']
	                }
	            });
	            
	            $('#win_user #confirm_password').textbox({
	                height: 28,
	                width: 300,
	                type: 'password',
	                required: userData ? false : true,
	                validType: {
	                	length: [4, 16],
	                	same: ['#win_user #login_password']
	                }
	            });
	            
	            $('#win_user #name').textbox({
	                height: 28,
	                width: 300,
	                required: true,
	                validType: {
	                	length: [1, 20]
	                }
	            });
	            
	            $('#win_user #user_group').combobox({
	    	        url: '${pageContext.request.contextPath}/api/GroupSearchAPI.json',
	                width: 300,
	                height: 28,
	                editable: false,
	                valueField: 'group_name',
	                textField: 'name',
	                multiple: true,
	                loadFilter: function(data) {
	                    return data.groups;
	                }
	            });
	            
	            if (userData) {
	                $('#win_user #login_name').textbox('setValue', userData.login_name);
	                $('#win_user #name').textbox('setValue', userData.name);
	                $('#win_user #user_group').combobox('setValues', userData.user_group);
	            }
	            
	            $('#win_user #btn_save').linkbutton({
	                onClick: function() {
	                    if ($('#win_user #user_form').form('validate')) {
	                        var paramData = {};
	                        paramData.login_name = $('#win_user #login_name').textbox('getValue');
	                        paramData.login_password = $('#win_user #login_password').textbox('getValue');
	                        paramData.name = $('#win_user #name').textbox('getValue');
	                        var groups = $('#win_user #user_group').combobox('getValues');
	                        paramData.user_group = groups.join(',');
	                        if (userData) {
	                            userAPI.update({
		                			onSuccess : function(data) {
		                				if (data.result) {
		                				    $('#user_list').datagrid('reload');
		                				    $('#win_user').window('close');
		                				} else {
		                				    $.messager.alert('<s:text name="title.error" />', $.format('<s:text name="messages.notification.fail" />', '编辑用户'));
		                				}
		                			},
		                			onAPIError : function(status, errors) {
		                				$.messager.alert('<s:text name="title.error" />', errors[0].msg);
		                			},
		                			onServerError : function(jqXHR, textStatus, errorThrown) {
		                				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
		                			}
		                		}, {
		                			param : JSON.stringify(paramData)
		                		});
	                        } else {
	                            userAPI.insert({
		                			onSuccess : function(data) {
		                				if (data.result) {
		                				    $('#user_list').datagrid('reload');
		                				    $('#win_user').window('close');
		                				} else {
		                				    $.messager.alert('<s:text name="title.error" />', $.format('<s:text name="messages.notification.fail" />', '新建用户'));
		                				}
		                			},
		                			onAPIError : function(status, errors) {
		                				$.messager.alert('<s:text name="title.error" />', errors[0].msg);
		                			},
		                			onServerError : function(jqXHR, textStatus, errorThrown) {
		                				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
		                			}
		                		}, {
		                			param : JSON.stringify(paramData)
		                		});
	                        }
	                    }
	                }
	            });
	            
	            $('#win_user #btn_cancel').linkbutton({
	                onClick: function() {
	                    $('#win_user').window('close');
	                }
	            });
	        },
	        onClose: function() {
	            $('#win_user #user_form').form('clear');
	        }
	    }).window('open');
	}
	
	function showGroupWin(groupData) {
	    $('#win_group').window({
	        onOpen: function() {
	            $('#win_group #group_name').textbox({
	                height: 28,
	                width: 300,
	                required: true,
	                readonly: groupData ? true : false,
	                validType: {
	                	length: [4, 20]
	                }
	            });
	            
	            $('#win_group #name').textbox({
	                height: 28,
	                width: 300,
	                required: groupData ? false : true,
	                validType: {
	                	length: [4, 20]
	                }
	            });
	            
	            if (groupData) {
	                $('#win_group #group_name').textbox('setValue', groupData.group_name);
	                $('#win_group #name').textbox('setValue', groupData.name);
	            }
	            
	            $('#win_group #btn_save').linkbutton({
	                onClick: function() {
	                    if ($('#win_group #group_form').form('validate')) {
	                        var paramData = {};
	                        paramData.group_name = $('#win_group #group_name').textbox('getValue');
	                        paramData.name = $('#win_group #name').textbox('getValue');
	                        if (groupData) {
	                            userAPI.updateGroup({
		                			onSuccess : function(data) {
		                				if (data.result) {
		                				    $('#group_list').datagrid('reload');
		                				    $('#win_group').window('close');
		                				} else {
		                				    $.messager.alert('<s:text name="title.error" />', $.format('<s:text name="messages.notification.fail" />', '编辑用户组'));
		                				}
		                			},
		                			onAPIError : function(status, errors) {
		                				$.messager.alert('<s:text name="title.error" />', errors[0].msg);
		                			},
		                			onServerError : function(jqXHR, textStatus, errorThrown) {
		                				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
		                			}
		                		}, {
		                			param : JSON.stringify(paramData)
		                		});
	                        } else {
	                            userAPI.insertGroup({
		                			onSuccess : function(data) {
		                				if (data.result) {
		                				    $('#group_list').datagrid('reload');
		                				    $('#win_group').window('close');
		                				} else {
		                				    $.messager.alert('<s:text name="title.error" />', $.format('<s:text name="messages.notification.fail" />', '新建用户组'));
		                				}
		                			},
		                			onAPIError : function(status, errors) {
		                				$.messager.alert('<s:text name="title.error" />', errors[0].msg);
		                			},
		                			onServerError : function(jqXHR, textStatus, errorThrown) {
		                				$.messager.alert('<s:text name="title.error" />', '<s:text name="messages.error.9004" />');
		                			}
		                		}, {
		                			param : JSON.stringify(paramData)
		                		});
	                        }
	                    }
	                }
	            });
	            
	            $('#win_group #btn_cancel').linkbutton({
	                onClick: function() {
	                    $('#win_group').window('close');
	                }
	            });
	        },
	        onClose: function() {
	            $('#win_group #group_form').form('clear');
	        }
	    }).window('open');
	}
});
</script>
<div class="easyui-panel" data-options="fit: true, closable: false, collapsible: false, minimizable: false, maximizable: false">
  <div id="user_manage_tabs" class="easyui-tabs" data-options="fit: true, border: false, pill: true">
    <div title="用户" data-options="closable:false, iconCls:'icon-man'" style="padding: 10px;">
      <table id="user_list"></table>
      <div id="user_toolbar">
        <label>关键字</label>
        <input id="search_keyword" type="text">&nbsp;&nbsp;
        <label>用户组</label>
        <input id="search_group">
        <a id="btn_search_user" href="#"></a>
        <a id="btn_add_user" href="#"></a>
      </div>
    </div>
    <div title="用户组" data-options="closable:false, iconCls:'icon-group'" style="padding: 10px;">
      <table id="group_list"></table>
      <div id="group_toolbar">
        <label>关键字</label>
        <input id="search_keyword" type="text">
        <a id="btn_search_group" href="#"></a>
        <a id="btn_add_group" href="#"></a>
      </div>
    </div>
  </div>
</div>
<div id="win_user" class="easyui-window" title="用户信息" data-options="modal:true, closed:true, collapsible:false, minimizable:false, maximizable:false, resizable:false, iconCls:'icon-man'" style="width:430px; height: auto; padding:10px;">
  <form id="user_form">
    <table id="user_table" class="edit_table">
      <tr>
        <th width="75">登录名</th>
        <td width="300"><input type="text" id="login_name"></td>
      </tr>
      <tr>
        <th>密码</th>
        <td><input type="text" id="login_password"></td>
      </tr>
      <tr>
        <th>确认密码</th>
        <td><input type="text" id="confirm_password"></td>
      </tr>
      <tr>
        <th>姓名</th>
        <td><input type="text" id="name"></td>
      </tr>
      <tr>
        <th>用户组</th>
        <td><input id="user_group"></td>
      </tr>
    </table>
    <input id="edit_index" type="hidden">
    <div style="text-align: right; margin-top: 5px;">
      <a id="btn_save" class="easyui-linkbutton" data-options="iconCls:'icon-save'">保存</a>
      <a id="btn_cancel" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'">取消</a>
    </div>
  </form>
</div>
<div id="win_group" class="easyui-window" title="用户组信息" data-options="modal:true, closed:true, collapsible:false, minimizable:false, maximizable:false, resizable:false, iconCls:'icon-group'" style="width:430px; height: auto; padding:10px;">
  <form id="group_form">
    <table id="group_table" class="edit_table">
      <tr>
        <th width="75">用户组名</th>
        <td width="300"><input type="text" id="group_name"></td>
      </tr>
      <tr>
        <th>表示名</th>
        <td><input type="text" id="name"></td>
      </tr>
    </table>
    <input id="edit_index" type="hidden">
    <div style="text-align: right; margin-top: 5px;">
      <a id="btn_save" class="easyui-linkbutton" data-options="iconCls:'icon-save'">保存</a>
      <a id="btn_cancel" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'">取消</a>
    </div>
  </form>
</div>